<?php
/**
 * Created by PhpStorm.
 * User: envision
 * Date: 2018-10-08
 * Time: 12:55
 */

namespace App\Http\Controllers\Api\V1\Manager;


use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\Category;
use App\Models\CheckRecord;
use App\Models\DeviceSetting;
use App\Models\Journey;
use App\Models\Record;
use App\Models\SelfPay;
use App\Models\User;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class CommonController extends Controller
{
    public function verify(Request $request)
    {
        $journeyCode = $request->journeyCode;
        $selfCode = $request->selfCode;
        if ($journeyCode) {
            $res = Journey::select()->where('journeyCode', $journeyCode)->count();
            if ($res) {
                return $this->apiResponse('', config('errorCode.CODE_REPEAT'));
            } else {
                return $this->apiResponse('');
            }
        }
        if ($selfCode) {
            $res = SelfPay::select()->where('selfCode', $selfCode)->count();
            if ($res) {
                return $this->apiResponse('', config('errorCode.CODE_REPEAT'));
            } else {
                return $this->apiResponse('');
            }
        }
    }

    public function recordExcel(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {

            $entension = $file->getClientOriginalExtension();
            $newName = time() . '.' . $entension;
            $file->move(public_path('uploads/excel'), $newName);    //把缓存文件移动到制定文件夹

            Excel::load(public_path("uploads/excel/" . $newName), function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });
            @unlink(public_path("uploads/excel/" . $newName));
            try {
                \DB::beginTransaction();
                $j = 0;
                $data = [];
                for ($i = 0; $i < count($res); $i++) {
                    if (!$res[$i][15]) {
                        $status = Category::where('categoryName', $res[$i][3])->where('parentId', 0)->first();
                        if (!$status) {
                            throw new \Exception("类型不存在:" . $res[$i][3]);
                        }
                        $data[$j]['categoryId'] = $status['categoryId'];
                        $data[$j]['submitTime'] = date('Y-m-d', strtotime($res[$i][9]));
                        $data[$j]['submitUnit'] = $res[$i][10];
                        $data[$j]['submitName'] = $res[$i][8];
                        $data[$j]['phone'] = $res[$i][6];
                        $data[$j]['userName'] = $res[$i][4];
                        $data[$j]['idCard'] = $res[$i][5];

                        $status = $res[$i][7] == 1 ? 2 : 1;
                        $data[$j]['status'] = $status;
                        $data[$j]['createTime'] = date('Y-m-d H:i:s', strtotime($res[$i][12]));
                        $data[$j]['record_id'] = $res[$i][0];
                        $j++;
                    }
                }
                if ($data) {
                    Record::insert($data);
                }
                \DB::commit();
                return $this->apiResponse('');
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("CommonController excel error message:" . $e->getMessage());
                return $this->apiResponse('', [
                    'errorCode' => "11011",
                    'errorMessage' => $e->getMessage()
                ]);
            }
        } else {
            return $this->apiResponse('', config('errorCode.UPLOAD_FILE_ERROR'));
        }
    }
    public function recordUpdateExcel(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {

            $entension = $file->getClientOriginalExtension();
            $newName = time() . '.' . $entension;
            $file->move(public_path('uploads/excel'), $newName);    //把缓存文件移动到制定文件夹

            Excel::load(public_path("uploads/excel/" . $newName), function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });
            @unlink(public_path("uploads/excel/" . $newName));
            try {
                \DB::beginTransaction();
                $j = 0;
                $data = [];

                for ($i = 0; $i < count($res); $i++) {
                  Record::where('record_id',$res[$i][0])->where('userName',$res[$i][1])->update(['idCard'=>$res[$i][2]]);
                }

                \DB::commit();
                return $this->apiResponse('');
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("CommonController excel error message:" . $e->getMessage());
                return $this->apiResponse('', [
                    'errorCode' => "11011",
                    'errorMessage' => $e->getMessage()
                ]);
            }
        } else {
            return $this->apiResponse('', config('errorCode.UPLOAD_FILE_ERROR'));
        }
    }
    public function categoryExcel(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {

            $entension = $file->getClientOriginalExtension();
            $newName = time() . '.' . $entension;
            $file->move(public_path('uploads/excel'), $newName);    //把缓存文件移动到制定文件夹

            Excel::load(public_path("uploads/excel/" . $newName), function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });
            @unlink(public_path("uploads/excel/" . $newName));
            try {
                \DB::beginTransaction();

                for ($i = 0; $i < count($res); $i++) {
                    if (!$res[$i][10]) {
                        $status = Category::where('categoryName', $res[$i][1])->where('parentId', "!=", 0)->first();
                        if (!$status) {
                            \Log::error("CommonController categoryExcel 类型不存在 message:" . $res[$i][1]);
                            var_dump( $res[$i][1]);
                            throw new \Exception("类型不存在:" . $res[$i][1]);

                        } else {
                            $category['cateId'] = $res[$i][0];
                             //   var_dump($status['categoryId'], $category['cateId'], $res[$i][1]);
                            Category::where('categoryId', $status['categoryId'])->update($category);
                        }
                    }
                }

                \DB::commit();
                return $this->apiResponse('');
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("CommonController categoryExcel error message:" . $e->getMessage());
                return $this->apiResponse('', [
                    'errorCode' => "11011",
                    'errorMessage' => $e->getMessage()
                ]);
            }
        } else {
            return $this->apiResponse('', config('errorCode.UPLOAD_FILE_ERROR'));
        }
    }

    public function recordDetailExcel(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {
            $entension = $file->getClientOriginalExtension();
            //  $newName = time() . '.' . $entension;
            //  $file->move(public_path('uploads/excel'), $newName);    //把缓存文件移动到制定文件夹
            $newName = "/1.xls";
            Excel::load("public/uploads/excel".$newName, function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });

            //   @unlink(public_path("uploads/excel/" . $newName));
            try {
                \DB::beginTransaction();
                $j = 0;
                $data = [];
                for ($i = 0; $i < count($res); $i++) {
                    if (!$res[$i][0]) {
                        continue;
                    }
                    $status = Record::where('record_id', $res[$i][3])->first();
                    if (!$status) {
                        \Log::error("CommonController recordDetailExcel record_id message:" . $res[$i][3]);
                        var_dump("record_id=" . $res[$i][3]);
                    }
                    CheckRecord::where('recordId', $status["recordId"])->delete();
                    $category = Category::where('cateId', $res[$i][2])->first();

                    if (!$category) {
                        \Log::error("CommonController recordDetailExcel cateId message:" . $res[$i][1]);
                        var_dump("cateId=" . $res[$i][2]);
                    }

                    if ($status && $category) {
                        $data[$j]['url'] = $res[$i][5];
                        $data[$j]['recordId'] = $status["recordId"];
                        $data[$j]['sort'] = $res[$i][4];
                        $data[$j]['categoryId'] = $category['categoryId'];
                        $j++;
                    }
                }

                $chunk_result = array_chunk($data, 1000);

                foreach ($chunk_result as $new_list) {
                    CheckRecord::insert($new_list);
                }
                \DB::commit();
                return $this->apiResponse('');
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("CommonController excel error message:" . $e->getMessage());
                return $this->apiResponse('', [
                    'errorCode' => "11011",
                    'errorMessage' => $e->getMessage()
                ]);
            }
        } else {
            return $this->apiResponse('', config('errorCode.UPLOAD_FILE_ERROR'));
        }
    }

    public function userExcel(Request $request)
    {
        $file = $request->file('file');
        if ($file->isValid()) {
            $entension = $file->getClientOriginalExtension();
              $newName = time() . '.' . $entension;
              $file->move(public_path('uploads/excel'), $newName);    //把缓存文件移动到制定文件夹

            Excel::load(public_path("uploads/excel/" . $newName), function ($reader) use (&$res) {
                $reader = $reader->getSheet(0);
                $res = $reader->toArray();
            });

            //   @unlink(public_path("uploads/excel/" . $newName));
            try {
                \DB::beginTransaction();
                $j = 0;
                $data = [];
                for ($i = 0; $i < count($res); $i++) {
                    $phone = $res[$i][3];

                    $status = User::where('phone',$phone)->first();
                    if(!$status){
                        $data[$j]['phone'] = $phone;
                        $data[$j]['userName'] =   $res[$i][1];
                        $data[$j]['idCard'] =   $res[$i][2];
                        $data[$j]['verifiedStatus'] =0;
                        if( $data[$j]['idCard']){
                            $data[$j]['verifiedStatus'] =1;
                        }
                        $address =   $res[$i][6];
                        $data[$j]['province'] = "";
                        $data[$j]['city'] =  "";
                        $data[$j]['area'] =  "";
                        $data[$j]['address'] =$address;
                        $createTime =  $res[$i][7];
                        $data[$j]['createTime'] =date('Y-m-d H:i:s',strtotime($createTime));
                        $data[$j]['accessToken'] =   encrypt($data[$j]['phone'] . time());
                        $data[$j]['password'] = md5("kt123456");
                        $userId = User::insertGetId($data[$j]);
                        DeviceSetting::create(['userId' => $userId]);
                        $j++;
                    }
                }
                \DB::commit();
                return $this->apiResponse('');
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("CommonController excel error message:" . $e->getMessage());
                return $this->apiResponse('', [
                    'errorCode' => "11011",
                    'errorMessage' => $e->getMessage()
                ]);
            }
        } else {
            return $this->apiResponse('', config('errorCode.UPLOAD_FILE_ERROR'));
        }
    }
}